package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.boruan.qq.zxgylibrary.utils.NavigateUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/8.
 * des: ....
 */

public class DrugPageDetailActivity extends BaseActivity {
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;
    @BindView(R2.id.ll_top_detail)
    LinearLayout llTopDetail;
    @BindView(R2.id.drugDetailWeb)
    WebView drugDetailWeb;

    private CustomDialog customDialog;
    private String detailId;
    private String shopId;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_drug_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        //暂时先这么弄，只要是进详情页面，返回药店首页就刷新，H5加一堆点击事件比较复杂，后面再慢慢优化
        ConstantInfo.isDetailRefresh = true;

        if (getIntent() != null){
            detailId = getIntent().getStringExtra("id");
            shopId = getIntent().getStringExtra("shopId");
        }
        customDialog = new CustomDialog(this, R.style.CustomDialog);
        customDialog.show();
        initWeb(ConstantInfo.baseUrl + "goodsDetail?type=android&shopId=" + shopId + "&skuId=" + detailId + "&token=" + ConstantInfo.h5UserToken);
    }

    @JavascriptInterface
    public void lookInstructions(){
        Intent intent = new Intent(DrugPageDetailActivity.this,DrugDirectionsActivity.class);
        intent.putExtra("shopId",shopId);
        intent.putExtra("skuId",detailId);
        startActivity(intent);
    }

    private void initWeb(final String richText) {

        //初始化webView
        new Handler().postDelayed(new Runnable() {
            @SuppressLint("JavascriptInterface")
            @Override
            public void run() {
                //drugDetailWeb = new NewWebView(DrugPageDetailActivity.this);
                drugDetailWeb.getSettings().setJavaScriptEnabled(true);
                drugDetailWeb.getSettings().setSupportZoom(true);
                drugDetailWeb.getSettings().setBuiltInZoomControls(true);
                drugDetailWeb.getSettings().setDisplayZoomControls(false);
                drugDetailWeb.setVerticalScrollBarEnabled(false);

                drugDetailWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                drugDetailWeb.getSettings().setLoadWithOverviewMode(true);
                drugDetailWeb.getSettings().setUseWideViewPort(true);
                drugDetailWeb.getSettings().setTextZoom(100);

                drugDetailWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//默认先不使用缓存
                drugDetailWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
                drugDetailWeb.getSettings().setDefaultTextEncodingName("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    drugDetailWeb.getSettings().setMixedContentMode(drugDetailWeb.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
                }
                drugDetailWeb.loadUrl(richText);
                drugDetailWeb.addJavascriptInterface(DrugPageDetailActivity.this, "control");
                //drugDetailWeb.setWebViewClient(new HtmlUtils.MyWebViewClient());
                drugDetailWeb.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        //customDialog.show();
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        customDialog.dismiss();
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();//接受所有网站的证书，忽略SSL错误
                        
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                        super.onReceivedError(view, webResourceRequest, webResourceError);
                        if (webResourceRequest.isForMainFrame()) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(DrugPageDetailActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        Toast.makeText(DrugPageDetailActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                        super.onReceivedHttpError(view, request, errorResponse);
                        // 这个方法在 android 6.0才出现
                        int statusCode = errorResponse.getStatusCode();
                        if (404 == statusCode || 500 == statusCode) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
                        }
                    }
                });

            }
        }, 100);

    }

    @JavascriptInterface
    public void addGoodsToCar(){

    }

//    @JavascriptInterface
//    public void callFaceAuthen(String arg) {
//        Bundle bundle = new Bundle();
//        bundle.putString("appId",arg);
//        ARouter.getInstance()
//                .build(ARouterConstant.ACTIVITY_FACE_HOME)
//                .with(bundle)
//                .navigation();
//    }

    @JavascriptInterface
    public void clickConfirmAuthorization(final String shopName) {
        //弹出用户确认授权框
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                authorizationPopWindow(shopName);
            }
        });
    }

    @JavascriptInterface
    public void clickBack() {
        finish();
    }

    private PopupWindow authorizationPop;

    public void authorizationPopWindow(String shopName) {
        authorizationPop = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_authorization_layout, null);
        TextView tvContent = (TextView)convertView.findViewById(R.id.tv_content);
        TextView tvCancel = (TextView) convertView.findViewById(R.id.tv_cancel);
        TextView tvOk = (TextView) convertView.findViewById(R.id.tv_ok);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
            }
        });

        tvContent.setText(shopName + ConstantInfo.shopNotice);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
                new NavigateUtils(DrugPageDetailActivity.this).navigateConfirmOrderActivity(shopId,-1);
//                Intent intent = new Intent(DrugPageDetailActivity.this, ConfirmOrderActivity.class);
//                intent.putExtra("shopId",shopId);
//                startActivity(intent);
            }
        });
        authorizationPop.setContentView(convertView);

        authorizationPop.setWidth(ConstantInfo.screenWidth - 180);
        authorizationPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        authorizationPop.setBackgroundDrawable(new ColorDrawable(0x00000000));
        authorizationPop.setTouchable(true);
        authorizationPop.setOutsideTouchable(false);
        /** 设置popupWindow动画 */
        authorizationPop.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        authorizationPop.setFocusable(false);
        authorizationPop.showAtLocation(findViewById(R.id.ll_add_web), Gravity.CENTER, 0, 0);
        authorizationPop.setOnDismissListener(new poponDismissListener());
    }

    /**
     * 重写activity中dispatchTouchEvent,在里面判断popupWindow是否显示来决定是否往下分发事件。
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (authorizationPop != null && authorizationPop.isShowing()) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * PopupWindow背景变暗
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @OnClick(R2.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (authorizationPop != null && authorizationPop.isShowing()) {
            authorizationPop.dismiss();
            return false;
        } else {

            if (keyCode == KeyEvent.KEYCODE_BACK && drugDetailWeb.canGoBack()) {
                drugDetailWeb.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (drugDetailWeb != null) {
            //加载null内容
            drugDetailWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            drugDetailWeb.clearHistory();
            //移除WebView
            ((ViewGroup) drugDetailWeb.getParent()).removeView(drugDetailWeb);
            //销毁VebView
            drugDetailWeb.destroy();
            //WebView置为null
            drugDetailWeb = null;
        }
        super.onDestroy();
    }

}
